package com.itheima.reggie.service.impl;

import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Page;
import com.itheima.reggie.exception.BusinessException;
import com.itheima.reggie.mapper.CategoryMapper;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishService;
import com.itheima.reggie.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.prefs.BackingStoreException;

@Service
public class CategoryServiceImpl implements CategoryService {
    @Autowired(required = false)
    private CategoryMapper categoryMapper;
    @Autowired(required = true)
    private DishService dishService;
    @Autowired(required = false)
    private SetmealService setmealService;
    @Override
    public Page<Category> selectByPage(Integer page, Integer pageSize) {
        List<Category> categories = categoryMapper.selectByPage((page - 1) * pageSize, pageSize);
        Integer count = categoryMapper.count();

        Page<Category> pageCategory = new Page<>();
        pageCategory.setRecords(categories);
        pageCategory.setTotal(count);

        return pageCategory;
    }

    @Override
    public Boolean add(Category category) {
        category.setCreateTime(LocalDateTime.now());
        category.setUpdateTime(LocalDateTime.now());

        Integer add = categoryMapper.add(category);

        return add>0;
    }

    @Override
    public Boolean update(Category category) {
        category.setUpdateTime(LocalDateTime.now());
        Integer update = categoryMapper.update(category);

        return update>0;
    }

    @Override
    public Boolean delete(Long id) {
        if (dishService.selectCountByCategoryId(id)){
            throw new BusinessException("该菜品分类下有菜品,不能删除");
        }
        if (setmealService.selectCountByCategoryId(id)){
            throw new BusinessException("该套餐分类下有套餐,不能删除");
        }

        Integer delete = categoryMapper.delete(id);
        return delete>0;
    }

    @Override
    public Category selectTypeById(Long type) {
        Category category = categoryMapper.selectTypeById(type);
        return category;
    }

    @Override
    public List<Category> selectAllByType(Integer type) {
        List<Category> categories = categoryMapper.selectAllByType(type);
        return categories;
    }

    @Override
    public Category selectByCategoryId(Long id) {
        Category category = categoryMapper.selectByCategoryId(id);
        return category;
    }
}
